package com.todo.strategy.online.application.frontend.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.todo.common.common.entity.response.BizPageResponse;
import com.todo.common.common.entity.response.BizResponse;
import com.todo.common.common.entity.response.page.PageResult;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.strategy.common.enums.TravelStatusEnum;
import com.todo.strategy.online.application.convert.StrategyConvert;
import com.todo.strategy.online.application.entity.bo.PlanSetBO;
import com.todo.strategy.online.application.entity.condition.PlanSetConditionBO;
import com.todo.strategy.online.application.frontend.service.PlanSetAggService;
import com.todo.strategy.online.application.remote.UserInfoRemoteService;
import com.todo.strategy.online.application.service.PlanSetService;
import com.todo.strategy.online.iface.request.*;
import com.todo.strategy.online.iface.response.PlanSetInfoVO;
import com.todo.strategy.online.iface.response.RecentlyPlanSetVO;
import com.todo.user.api.response.BaseUserInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (PlanSet)表服务实现类
 *
 * @author zhangwenxiang
 * @since 2024-03-04 00:19:47
 */
@Slf4j
@Service("planSetAggService")
public class PlanSetAggServiceImpl implements PlanSetAggService {

    @Resource
    private PlanSetService planSetService;
    @Resource
    private UserInfoRemoteService userInfoRemoteService;


    @Override
    public BizResponse<Boolean> insertPlanSet(InsertPlanSetParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        PlanSetBO request = StrategyConvert.convertToPlanSetBO(param);
        Boolean insertResult = planSetService.insertPlanSet(request);
        return BizResponse.success(insertResult);
    }

    @Override
    public BizResponse<Boolean> removePlanSet(RemovePlanSetParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        Boolean removeResult = planSetService.removePlanSetByIdList(param.get_user().getUserId(), param.getPlanIdList());
        return BizResponse.success(removeResult);
    }

    @Override
    public BizResponse<Boolean> updatePlanSetById(UpdatePlanSetParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        PlanSetBO request = StrategyConvert.convertToPlanSetBO(param);
        Boolean updateResult = planSetService.updatePlanSet(request);
        return BizResponse.success(updateResult);
    }

    @Override
    public BizPageResponse<PlanSetInfoVO> queryPlanSetByUser(QueryPlanSetByUserParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        BizResponse<BaseUserInfoResponse> userAccountResponse = userInfoRemoteService.queryBaseUserAccountInfoByUserId(param.getTargetUserId());
        if (userAccountResponse == null || !userAccountResponse.isSuccess() || userAccountResponse.getData() == null) {
            log.error("PlanSetAggService#queryPlanSetByUser 根据用户id查询计划清单信息失败，当前用户不存在 入参：【{}】", JSONObject.toJSONString(param));
            return BizPageResponse.operationFailed("当前用户不存在");
        }
        PlanSetConditionBO request = new PlanSetConditionBO();
        request.setUserId(param.getTargetUserId());
        request.setPageIndex(param.getPageIndex());
        request.setPageSize(param.getPageSize());
        request.setPageIndex(param.getPageIndex());
        PageResult<PlanSetBO> result = planSetService.queryPlanSetByCondition(request);
        return BizPageResponse.success(StrategyConvert.buildPagePlanSetBaseResponseList(userAccountResponse.getData(), result));
    }

    @Override
    public BizResponse<RecentlyPlanSetVO> queryRecentlyPlanSetList(QueryRecentlyPlanSetListParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }

        BizResponse<BaseUserInfoResponse> userAccountResponse = userInfoRemoteService.queryBaseUserAccountInfoByUserId(param.get_user().getUserId());
        if (userAccountResponse == null || !userAccountResponse.isSuccess() || userAccountResponse.getData() == null) {
            log.error("PlanSetAggService#queryRecentlyPlanSetList 根据用户id查询最近计划集合信息失败，当前用户不存在 入参：【{}】", JSONObject.toJSONString(param));
            return BizResponse.operationFailed("当前用户不存在");
        }

        //1、当前时间前一周和后一周的旅行计划
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = now.minusDays(7);
        LocalDateTime endTime = now.plusDays(7);
        List<PlanSetBO> planSetBOList = planSetService.queryPlanSetListByTime(param.get_user().getUserId(), startTime, endTime);
        if (CollectionUtils.isEmpty(planSetBOList)) {
            return BizResponse.success();
        }
        // 2、优先级：当前进行中的 》 未开始的 》 已经结束的
        Map<Integer, List<PlanSetBO>> collect = planSetBOList.stream().collect(Collectors.groupingBy(PlanSetBO::getTravelStatus));
        List<PlanSetInfoVO> result = new ArrayList<>();
        if (collect.containsKey(TravelStatusEnum.IN_PROGRESS.getType())) {
            List<PlanSetInfoVO> planSetInfoVOS = StrategyConvert.buildPagePlanSetBaseResponseList(userAccountResponse.getData(), collect.get(TravelStatusEnum.IN_PROGRESS.getType()));
            if (CollectionUtils.isNotEmpty(planSetInfoVOS)) {
                result.addAll(planSetInfoVOS);
            }
        }
        if (collect.containsKey(TravelStatusEnum.NOT_STARTED.getType())) {
            List<PlanSetInfoVO> planSetInfoVOS = StrategyConvert.buildPagePlanSetBaseResponseList(userAccountResponse.getData(), collect.get(TravelStatusEnum.NOT_STARTED.getType()));
            if (CollectionUtils.isNotEmpty(planSetInfoVOS)) {
                result.addAll(planSetInfoVOS);
            }
        }
        if (collect.containsKey(TravelStatusEnum.ENDED.getType())) {
            List<PlanSetInfoVO> planSetInfoVOS = StrategyConvert.buildPagePlanSetBaseResponseList(userAccountResponse.getData(), collect.get(TravelStatusEnum.ENDED.getType()));
            if (CollectionUtils.isNotEmpty(planSetInfoVOS)) {
                result.addAll(planSetInfoVOS);
            }
        }
        RecentlyPlanSetVO recentlyPlanSetVO = new RecentlyPlanSetVO();
        recentlyPlanSetVO.setPlanSetInfoList(result);
        return BizResponse.success(recentlyPlanSetVO);
    }
}
